import baostock as bs
import pandas as pd
import datetime
import backtrader as bt
import easyquotation
import pymysql


from util.daylink import daylink


class GetMysqlDat() :


    def  getDataDayFeeds(self,code,getNow):
        code = code.split('.', 1)
        fromdate = daylink().get_day_of_day(-220)
        todate = daylink().get_day_of_day(0)
        df_init=self.getDataDay(code[1],getNow,fromdate,todate)
        df_init.date = pd.to_datetime(df_init.date)
        data = bt.feeds.PandasData(dataname=df_init,
                                   datetime='date',
                                   openinterest=-1,
                                   open='open',
                                   high='high',
                                   low='low',
                                   close='close',
                                   fromdate=fromdate,
                                   todate=todate)

        return data





    def getDataDay(self,code,getNow,fromdate,todate):
        try:
            #code = stk_code.split('.', 1)
            #fromdate = daylink().get_day_of_day(-9000)
            #todate = daylink().get_day_of_day(0)
            # 打开数据库连接
            db = pymysql.connect(host='101.35.200.120', port=3306, user='root', passwd='ljf123456', db='gp',charset='utf8')
            # 使用cursor()方法获取操作游标
            cursor = db.cursor()
            sSql = """select id, time,opening_price,max_price,min_price,close_price from record_data_%s  where  time  >= '%s' and  time  <= '%s' """ % (code,fromdate,todate)
            #print(sSql)
            cursor.execute(sSql)
            sResults = cursor.fetchall()
            adjustSql = """select id,operate_date,fore_adjust_factor,back_adjust_factor from adjust_factor  where  code = %s  ORDER BY operate_date ASC """ % (code)
            cursor.execute(adjustSql)
            adjustResults = cursor.fetchall()
            if (len(sResults) > 0):
                result_list = []
                for row in sResults:
                    time =row[1]
                    opening_price =row[2]
                    max_price = row[3]
                    min_price = row[4]
                    close_price = row[5]
                    #time = datetime.datetime.strptime(time, '%Y-%m-%d')
                    if (len(adjustResults) > 0):
                        for adjustrow in adjustResults:
                            operate_date = adjustrow[1]
                            fore_adjust_factor=adjustrow[2]
                            back_adjust_factor = adjustrow[3]
                            delta = operate_date - time
                            if delta.days >= 0:
                                opening_price=opening_price*fore_adjust_factor
                                min_price = min_price * fore_adjust_factor
                                max_price = max_price * fore_adjust_factor
                                close_price = close_price * fore_adjust_factor
                                break
                    member = [time,code, opening_price, max_price, min_price, close_price]
                    result_list.append(member)
                if getNow == True:
                    quotation = easyquotation.use('tencent')  # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
                    newdata = quotation.real(code, prefix=False).get(code)  # 支持直接指定前缀，如 'sh000001'
                    newLow = float(newdata.get('low'))
                    newNow = float(newdata.get('now'))
                    newHigh = float(newdata.get('high'))
                    newOpen = float(newdata.get('open'))
                    nowdate= daylink().get_day_of_day(0)
                    member = [ nowdate,code, newOpen, newHigh, newLow, newNow]
                    result_list.append(member)
            df_init = pd.DataFrame(result_list, columns=['date','code', 'open', 'high', 'low', 'close'])
            df_init = df_init.astype({ 'high': 'float', 'open': 'float', 'close': 'float', 'low': 'float'})
            return  df_init
        except Exception as e:
            print(e)
            return  None

if __name__ == '__main__':
      fromdate = daylink().get_day_of_day(-9000)
      todate = daylink().get_day_of_day(0)
      m= GetMysqlDat()
      print(m.getDataDay('300178',True,fromdate,todate))